//
//  AlarmListViewController.m
//  Voice2AlarmNote
//
//  Created by onemade on 14-10-28.
//  Copyright (c) 2014年 CNPC. All rights reserved.
//

#import "AlarmListViewController.h"

@interface AlarmListViewController ()<AlarmDetailCellDelegate>

@end

@implementation AlarmListViewController

#pragma mark - viewController life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.collectionView setDelegate:self];
    [self.collectionView setDataSource:self];
    
    [self.collectionView registerClass:[AlarmDetailCell class] forCellWithReuseIdentifier:@"AlarmDetaillCell"];
    UIMenuItem *menuItem = [[UIMenuItem alloc] initWithTitle:@"删除"
                                                      action:@selector(customAction:)];
    [[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObject:menuItem]];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self loadAllAlarm];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - collectionViewDelegate methods
- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    return YES; 
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    NSLog(@"performAction");
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.allAlarms count];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    AlarmDetailCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AlarmDetaillCell"
                                                                           forIndexPath:indexPath];
    cell.layer.borderColor = [UIColor lightGrayColor].CGColor;
    cell.layer.borderWidth = 1;
    cell.layer.cornerRadius = 20;
    
    Alarm *alarm = [self.allAlarms objectAtIndex:row];
    
    NSDate *now = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"yyyy/MM/dd HH:mm"];
    
    if ([[dateFormatter dateFromString:alarm.alarmTime] timeIntervalSinceDate:now] > 0.0 ) {
        [self setAlarmNotification:[dateFormatter dateFromString:alarm.alarmTime]];
    }
    cell.alarmContent.text = alarm.alarmContent;
    cell.alertDate.text = alarm.alarmTime;
    cell.curAlarm = alarm;
    cell.delegate = self;
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    Alarm *alarm = [self.allAlarms objectAtIndex:row];
    if (alarm != nil) {
        AlarmViewController *alarmViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"alarmViewController"];
        alarmViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [self.navigationController presentViewController:alarmViewController animated:YES completion:^{
            alarmViewController.currentAlarm = alarm;
            alarmViewController.isUpdate = YES;
            alarmViewController.contentTextView.text = alarm.alarmContent;
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat: @"yyyy/MM/dd HH:mm"];
            [alarmViewController.datePicker setDate:[dateFormatter dateFromString:alarm.alarmTime]];
        }];
    }
}

#pragma mark - UIMenuController required methods (Might not be needed on iOS 7)
- (BOOL)canBecomeFirstResponder {
    // NOTE: This menu item will not show if this is not YES!
    return YES;
}

#pragma mark - button click actions

#pragma mark - customize methods
-(void)loadAllAlarm
{
    self.allAlarms = [[AlarmTool sharedAlarmTool] fetchAllAlarms];
    [self.collectionView reloadData];
}

-(NSString *)formatDate:(NSDate *)date
{
    NSDate *selected = date;
    // 创建一个日期格式器
    NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
    // 为日期格式器设置格式字符串
    [dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm"];
    // 使用日期格式器格式化日期、时间
    NSString *destDateString = [dateFormatter stringFromDate:selected];
    
    return destDateString;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    NSLog(@"canPerformAction");
    // The selector(s) should match your UIMenuItem selector
    if (action == @selector(customAction:)) {
        return YES;
    }
    return NO;
}

-(void)setAlarmNotification:(NSDate *)time
{
    NSDate *now = [NSDate date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *currentDateComponents = [gregorian components:(NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit) fromDate:now];
     NSDateComponents *alarmDateComponents = [gregorian components:(NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit) fromDate:time];
    NSInteger currentHour = [currentDateComponents hour];
    NSInteger currentMin = [currentDateComponents minute];
    NSInteger alarmHour = [alarmDateComponents hour];
    NSInteger alarmMin = [alarmDateComponents minute];
    NSInteger currentTotal = currentHour*3600 +currentMin * 60;
    NSInteger alarmTotal = alarmHour*3600 + alarmMin * 60;
    NSInteger ontime = alarmTotal - currentTotal;
    
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:ontime];
    notification.soundName = @"cat.caf";
    notification.alertBody = [NSString stringWithFormat:@"Alarm on : %@", time];
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

#pragma mark - Custom Action(s) for iOS 6.0
- (void)customAction:(id)sender {
    NSLog(@"custom action! %@", sender);
}

// iOS 7.0 custom delegate method for the Cell to pass back a method for what custom button in the UIMenuController was pressed
- (void)customAction:(id)sender forCell:(AlarmDetailCell *)cell {
    [self.collectionView performBatchUpdates:^{
        NSInteger index = [self.allAlarms indexOfObject:cell.curAlarm];
        [self.allAlarms removeObjectAtIndex:index];
        NSIndexPath *indexPath =[NSIndexPath indexPathForRow:index inSection:0];
        [self.collectionView deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];
    } completion:^(BOOL finished) {
        [[AlarmTool sharedAlarmTool] deleteAlarm:cell.curAlarm];
        [self.collectionView reloadData];
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
